<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Plus, Loading, Link } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { useUserStore } from '@/stores/useUserStore'
import { teamApi } from '@/api/request'

// ===== 状态管理 =====
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 团队相关状态
const teams = ref([])
const selectedTeam = ref('')
const showCreateTeamForm = ref(false)
const newTeamName = ref('')
const teamFormRef = ref(null)

// 成员相关状态
const teamMembers = ref([])
const showAddMemberForm = ref(false)
const newMemberUsername = ref('')
const search = ref('')

// 角色相关状态
const roles = ref([])
const editingMember = ref(null)
const showEditRoleDialog = ref(false)

// 邀请链接相关状态
const inviteLink = ref('')
const showInviteLink = ref(false)

// 通用状态
const loading = ref(false)
const errorMessage = ref('')

// ===== 表单验证规则 =====
const teamFormRules = {
  teamname: [
    { required: true, message: '请输入团队名称', trigger: 'blur' },
    {
      min: 2,
      max: 15,
      message: '团队名称长度必须在2到15个字符之间',
      trigger: 'change'
    },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/,
      message: '团队名称只能包含中文、字母和数字',
      trigger: 'change'
    },
    {
      validator: async (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        try {
          const response = await teamApi.getTeams()
          if (response.data.code === 200) {
            const existingTeams = response.data.data.map(
              (team) => team.teamname
            )
            if (existingTeams.includes(value)) {
              callback(new Error('该团队名称已存在'))
            } else {
              callback()
            }
          } else {
            callback(new Error('验证团队名称失败'))
          }
        } catch (error) {
          console.error('验证团队名称失败:', error)
          callback(new Error('验证团队名称时出错，请重试'))
        }
      },
      trigger: ['blur', 'change']
    }
  ]
}

// ===== 工具函数 =====
// 检查登录状态
const checkAuth = () => {
  if (!userStore.isLoggedIn || !userStore.token) {
    ElMessage.error('请先登录')
    window.location.href = '/login'
    return false
  }
  return true
}

// ===== 团队相关方法 =====
// 获取团队列表
const handleTeamSelectFocus = async () => {
  if (!checkAuth()) return

  loading.value = true
  try {
    const response = await teamApi.getTeams()
    if (response.data.code === 200) {
      const uniqueTeams = [
        ...new Set(response.data.data.map((team) => team.teamname))
      ]
      teams.value = uniqueTeams.sort()
    } else {
      ElMessage.error(response.data.message || '获取团队列表失败')
    }
  } catch (error) {
    console.error('获取团队列表失败:', error)
    ElMessage.error('获取团队列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 创建新团队
const submitNewTeam = async () => {
  if (!teamFormRef.value) return

  try {
    await teamFormRef.value.validate()
    loading.value = true
    errorMessage.value = ''

    if (teams.value.includes(newTeamName.value)) {
      ElMessage.warning('团队名称已存在，请使用其他名称')
      return
    }

    const response = await teamApi.createTeam(newTeamName.value)
    if (response.data.code === 200) {
      ElMessage.success('创建团队成功')
      await handleTeamSelectFocus()
      newTeamName.value = ''
      showCreateTeamForm.value = false
    } else {
      ElMessage.error(response.data.message || '创建团队失败')
    }
  } catch (error) {
    if (error.message) return // 表单验证错误
    console.error('创建团队失败:', error)
    ElMessage.error(error.response?.data?.message || '创建团队失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// ===== 成员相关方法 =====
// 获取团队成员列表
const fetchTeamMembers = async () => {
  if (!selectedTeam.value || !checkAuth()) return

  loading.value = true
  errorMessage.value = ''

  try {
    const response = await teamApi.getTeamMembers(selectedTeam.value)
    if (response.data.code === 200) {
      teamMembers.value = response.data.data.records.map((member) => ({
        name: member.teammember,
        role: member.role
      }))
    } else {
      errorMessage.value = response.data.message || '获取团队成员失败'
    }
  } catch (error) {
    console.error('获取团队成员失败:', error)
    errorMessage.value =
      error.response?.data?.message || '获取团队成员失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 添加新成员
const submitNewMember = async () => {
  if (!selectedTeam.value) {
    ElMessage.warning('请先选择团队')
    return
  }

  if (newMemberUsername.value.trim() === '') {
    ElMessage.warning('请填写用户名')
    return
  }

  loading.value = true
  errorMessage.value = ''

  try {
    const addResponse = await teamApi.joinTeamByLeader({
      username: newMemberUsername.value,
      teamname: selectedTeam.value
    })

    if (addResponse.data.code === 600) {
      ElMessage.error('该用户不存在')
      return
    }

    if (addResponse.data.code === 200) {
      await fetchTeamMembers()
      newMemberUsername.value = ''
      showAddMemberForm.value = false
      ElMessage.success('添加成员成功')
    } else {
      errorMessage.value = addResponse.data.message || '添加成员失败'
    }
  } catch (error) {
    console.error('操作失败:', error)
    if (error.response?.data?.code === 600) {
      ElMessage.error('该用户不存在')
    } else {
      errorMessage.value =
        error.response?.data?.message || '操作失败，请稍后重试'
    }
  } finally {
    loading.value = false
  }
}

// 删除团队成员
const deleteMember = async (member) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除成员 ${member.name} 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    const response = await teamApi.deleteTeamMember({
      username: member.name,
      teamname: selectedTeam.value
    })

    if (response.data.code === 200) {
      await fetchTeamMembers()
      ElMessage.success('删除成员成功')
    } else {
      ElMessage.error(response.data.message || '删除成员失败')
    }
  } catch (error) {
    if (error === 'cancel') return
    console.error('删除成员失败:', error)
    ElMessage.error(error.response?.data?.message || '删除成员失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// ===== 角色相关方法 =====
// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await teamApi.getRoles()
    if (response.data.code === 200) {
      roles.value = response.data.data.map((roleName) => ({
        label: roleName,
        value: roleName
      }))
    } else {
      ElMessage.error(response.data.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败，请稍后重试')
  }
}

// 打开修改角色对话框
const handleEditRole = (member) => {
  editingMember.value = { ...member }
  showEditRoleDialog.value = true
  if (roles.value.length === 0) {
    fetchRoles()
  }
}

// 提交角色修改
const submitRoleChange = async () => {
  if (!editingMember.value) return

  loading.value = true
  try {
    await teamApi.modifyTeamMemberRole({
      username: editingMember.value.name,
      teamname: selectedTeam.value,
      role: editingMember.value.role
    })
    await fetchTeamMembers()
    showEditRoleDialog.value = false
    ElMessage.success('修改角色成功')
  } catch (error) {
    console.error('修改角色失败:', error)
    ElMessage.error(error.response?.data?.message || '修改角色失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// ===== 邀请链接相关方法 =====
// 生成邀请链接
const generateInviteLink = async () => {
  if (!selectedTeam.value) {
    ElMessage.warning('请先选择团队')
    return
  }

  loading.value = true
  try {
    const response = await teamApi.generateInviteLink(selectedTeam.value)
    if (response.data.code === 200) {
      inviteLink.value = response.data.data
      showInviteLink.value = true
    } else {
      ElMessage.error(response.data.message || '生成邀请链接失败')
    }
  } catch (error) {
    console.error('生成邀请链接失败:', error)
    ElMessage.error('生成邀请链接失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 复制邀请链接
const copyInviteLink = () => {
  navigator.clipboard
    .writeText(inviteLink.value)
    .then(() => ElMessage.success('邀请链接已复制到剪贴板'))
    .catch(() => ElMessage.error('复制失败，请手动复制'))
}

// 处理邀请链接加入团队
const handleJoinTeam = async (inviteLink) => {
  try {
    loading.value = true
    console.log('正在处理邀请链接:', inviteLink)
    const res = await teamApi.joinTeamByLink({
      link: inviteLink
    })
    console.log('加入团队响应:', res)
    if (res.data.code === 200) {
      ElMessage.success('加入团队成功')
      await handleTeamSelectFocus()
      if (res.data.data?.teamname) {
        selectedTeam.value = res.data.data.teamname
        await fetchTeamMembers()
      }
      router.replace({
        path: '/team-bind',
        query: {}
      })
    } else {
      ElMessage.error(res.data.message || '加入失败')
    }
  } catch (error) {
    console.error('加入团队出错：', error)
    if (error.response?.data?.code === 600) {
      ElMessage.error('该用户不存在')
    } else {
      ElMessage.error(
        error.response?.data?.message || '加入团队失败，请稍后重试'
      )
    }
  } finally {
    loading.value = false
  }
}

// ===== 计算属性 =====
// 过滤表格数据
const filterTableData = computed(() =>
  teamMembers.value.filter(
    (data) =>
      !search.value ||
      data.name.toLowerCase().includes(search.value.toLowerCase()) ||
      data.role.toLowerCase().includes(search.value.toLowerCase())
  )
)

// ===== 生命周期钩子 =====
onMounted(() => {
  const inviteLink = route.query.invite
  console.log('邀请链接参数:', inviteLink)

  if (inviteLink) {
    if (!userStore.isLoggedIn) {
      router.push({
        path: '/login',
        query: { redirect: route.fullPath }
      })
    } else {
      if (!userStore.token) {
        ElMessage.error('登录已过期，请重新登录')
        router.push({
          path: '/login',
          query: { redirect: route.fullPath }
        })
        return
      }
      handleJoinTeam(inviteLink)
    }
  }
  fetchRoles()
})

// ===== 事件处理 =====
const handleTeamChange = () => {
  fetchTeamMembers()
}
</script>

<template>
  <div class="team-bind-container">
    <div class="header">
      <div class="left">
        <h2 class="title">团队管理</h2>
      </div>
      <div class="right">
        <el-button
          type="primary"
          @click="showCreateTeamForm = true"
          class="create-team-btn"
        >
          <el-icon><Plus /></el-icon>创建团队
        </el-button>
        <el-select
          v-model="selectedTeam"
          placeholder="请选择团队"
          class="team-select"
          @change="handleTeamChange"
          @focus="handleTeamSelectFocus"
        >
          <el-option
            v-for="team in teams"
            :key="team"
            :label="team"
            :value="team"
          />
        </el-select>
        <el-button
          type="primary"
          @click="showAddMemberForm = !showAddMemberForm"
          class="add-btn"
          :disabled="!selectedTeam"
        >
          <el-icon><Plus /></el-icon
          >{{ showAddMemberForm ? '取消' : '添加成员' }}
        </el-button>
      </div>
    </div>

    <div v-if="loading" class="loading">
      <el-icon class="loading-spinner"><Loading /></el-icon>加载中...
    </div>

    <el-alert
      v-if="errorMessage"
      :title="errorMessage"
      type="error"
      show-icon
      class="error-message"
    />

    <div class="team-list" v-if="selectedTeam">
      <el-table :data="filterTableData" stripe border style="width: 100%">
        <el-table-column prop="name" label="成员姓名" min-width="180" />
        <el-table-column prop="role" label="成员角色" min-width="180" />
        <el-table-column
          align="right"
          width="240"
          class-name="operation-column"
        >
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEditRole(row)">
              修改角色
            </el-button>
            <el-button type="danger" size="small" @click="deleteMember(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-empty v-else description="请选择团队查看成员列表" />

    <el-dialog
      v-model="showAddMemberForm"
      title="添加团队成员"
      width="500px"
      destroy-on-close
    >
      <div class="add-member-container">
        <div class="direct-add-section">
          <h3 class="section-title">方式一：队长直接添加</h3>
          <el-form class="member-form">
            <el-form-item label="成员用户名">
              <el-input
                v-model="newMemberUsername"
                placeholder="请输入成员用户名"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="submitNewMember"
                :loading="loading"
                >确认添加</el-button
              >
            </el-form-item>
          </el-form>
        </div>

        <el-divider>或者</el-divider>

        <div class="invite-section">
          <h3 class="section-title">方式二：邀请链接</h3>
          <p class="section-desc">生成邀请链接，将链接发送给要邀请的成员</p>
          <el-button
            type="primary"
            plain
            @click="generateInviteLink"
            :loading="loading"
            class="generate-link-btn"
          >
            <el-icon><Link /></el-icon>生成邀请链接
          </el-button>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddMemberForm = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showCreateTeamForm"
      title="创建新团队"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="teamFormRef"
        :model="{ teamname: newTeamName }"
        :rules="teamFormRules"
        class="team-form"
      >
        <el-form-item label="团队名称" prop="teamname">
          <el-input
            v-model="newTeamName"
            placeholder="请输入团队名称"
            clearable
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showCreateTeamForm = false">取消</el-button>
          <el-button type="primary" @click="submitNewTeam" :loading="loading"
            >确认创建</el-button
          >
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showInviteLink"
      title="邀请链接"
      width="500px"
      destroy-on-close
    >
      <el-input
        v-model="inviteLink"
        :rows="4"
        type="textarea"
        placeholder="邀请链接"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showInviteLink = false">取消</el-button>
          <el-button type="primary" @click="copyInviteLink"
            >复制邀请链接</el-button
          >
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showEditRoleDialog"
      title="修改角色"
      width="500px"
      destroy-on-close
    >
      <el-form :model="editingMember" class="team-form">
        <el-form-item label="角色">
          <el-select
            v-model="editingMember.role"
            class="role-select"
            placeholder="请选择角色"
          >
            <el-option
              v-for="role in roles"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showEditRoleDialog = false">取消</el-button>
          <el-button type="primary" @click="submitRoleChange" :loading="loading"
            >确认修改</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.team-bind-container {
  padding: 32px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;

  .left {
    .title {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #1e1e2d;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        bottom: -8px;
        left: 0;
        width: 40%;
        height: 2px;
        background: linear-gradient(90deg, #7367f0 0%, transparent 100%);
      }
    }
  }

  .right {
    display: flex;
    align-items: center;
    gap: 16px;

    .create-team-btn {
      background: linear-gradient(135deg, #7367f0 0%, #9f94ff 100%);
      border: none;
      padding: 12px 24px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(115, 103, 240, 0.3);
      }
    }

    .team-select {
      width: 220px;

      :deep(.el-input__wrapper) {
        box-shadow: 0 2px 12px rgba(115, 103, 240, 0.1);
        border-radius: 8px;
        padding: 0 16px;

        &:hover {
          box-shadow: 0 4px 16px rgba(115, 103, 240, 0.15);
        }
      }
    }

    .add-btn {
      background: #ffffff;
      border: 2px solid #7367f0;
      color: #7367f0;
      padding: 10px 24px;
      transition: all 0.3s ease;

      &:hover:not(:disabled) {
        background: #7367f0;
        color: #ffffff;
        transform: translateY(-2px);
      }

      &:disabled {
        border-color: #e0e0e0;
        color: #909399;
      }
    }
  }
}

.loading {
  text-align: center;
  padding: 40px 0;
  color: #909399;

  .loading-spinner {
    margin-right: 8px;
    animation: rotating 2s linear infinite;
  }
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.error-message {
  margin-bottom: 16px;
}

.team-list {
  margin-top: 24px;

  :deep(.el-table) {
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);

    th {
      background-color: #f8f8fb !important;
      color: #1e1e2d;
      font-weight: 600;
      padding: 16px 24px;
      border-bottom: 1px solid rgba(115, 103, 240, 0.1);
    }

    td {
      padding: 16px 24px;
      color: #6e6b7b;
      border-bottom: 1px solid rgba(115, 103, 240, 0.1);
    }

    .operation-column {
      .cell {
        display: inline-flex;
        justify-content: flex-end;
        gap: 8px;
        width: 100%;
      }

      .el-button {
        margin: 0;
        padding: 8px 16px;
        height: 32px;
        line-height: 1;
        font-size: 14px;
        border-radius: 6px;
        transition: all 0.3s ease;

        &--primary {
          background: linear-gradient(135deg, #7367f0 0%, #9f94ff 100%);
          border: none;
          color: #ffffff;
          min-width: 76px;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(115, 103, 240, 0.3);
          }
        }

        &--danger {
          background: #ffffff;
          border: 1px solid #ff4d4f;
          color: #ff4d4f;
          min-width: 52px;

          &:hover {
            background: #ff4d4f;
            color: #ffffff;
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(255, 77, 79, 0.3);
          }
        }
      }
    }
  }
}

.add-member-container {
  padding: 24px 0;

  .section-title {
    font-size: 18px;
    color: #1e1e2d;
    margin: 0 0 20px;
    font-weight: 600;
  }

  .section-desc {
    color: #6e6b7b;
    font-size: 14px;
    margin: 12px 0;
  }

  .el-divider {
    margin: 32px 0;
  }
}

.direct-add-section {
  .member-form {
    :deep(.el-input__wrapper) {
      box-shadow: 0 2px 12px rgba(115, 103, 240, 0.1);
      border-radius: 8px;
      padding: 0 16px;

      &:hover {
        box-shadow: 0 4px 16px rgba(115, 103, 240, 0.15);
      }
    }
  }
}

.invite-section {
  text-align: center;
  padding: 24px 0;

  .generate-link-btn {
    background: #ffffff;
    border: 2px solid #7367f0;
    color: #7367f0;
    padding: 12px 32px;
    margin-top: 20px;
    transition: all 0.3s ease;

    &:hover {
      background: #7367f0;
      color: #ffffff;
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(115, 103, 240, 0.3);
    }
  }
}

:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 32px rgba(115, 103, 240, 0.15);

  .el-dialog__header {
    margin: 0;
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #1e1e2d;
    }
  }

  .el-dialog__body {
    padding: 24px;
  }

  .el-dialog__footer {
    border-top: 1px solid #f0f0f0;
    padding: 16px 24px;
  }

  .el-button {
    padding: 10px 24px;
    border-radius: 8px;
    transition: all 0.3s ease;

    &--primary {
      background: linear-gradient(135deg, #7367f0 0%, #9f94ff 100%);
      border: none;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(115, 103, 240, 0.3);
      }
    }
  }
}
</style>
